package algorithm.tic_tac_toe;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ChessBoard implements Serializable {
	private static final long serialVersionUID = -199823804762183950L;
	private char[][] board;
	public static final int N = 3;
	public static final char HUMAN = 'H';
	public static final char COMPUTER = 'C';
	private static final char BLANK = '_';

	public static final short MIN_INFINITY = -1;
	public static final short MAX_INFINITY = 1;
	public static final short DRAW = 0;

	public boolean checkPlayerWin(char player) {
		boolean retRow = true;
		boolean retCol = true;
		boolean retClinodiagonal = true;
		boolean retDiagonal = true;
		int i, j;
		for (i = 0; i < N; i++, retRow = retCol = true) {
			for (j = 0; j < N; j++) {
				if (board[i][j] != player)
					retRow = false;
				if (board[j][i] != player)
					retCol = false;
			}

			if (retRow == true || retCol == true)
				return true;
		}

		for (i = 0, j = N - 1; i < N; j--, i++) {
			if (board[i][j] != player)
				retClinodiagonal = false;
			if (board[i][i] != player)
				retDiagonal = false;
		}
		if (retDiagonal == true || retClinodiagonal == true)
			return true;

		return false;
	}

	public boolean setChessHuman(int x, int y) {
		try {
			if (board[y][x] == BLANK) {
				board[y][x] = HUMAN;
				return true;
			} else
				return false;
		} catch (ArrayIndexOutOfBoundsException e) {
			return false;
		}
	}

	public boolean setChessComputer(int x, int y) {
		try {
			if (board[y][x] == BLANK) {
				board[y][x] = COMPUTER;
				return true;
			} else
				return false;
		} catch (ArrayIndexOutOfBoundsException e) {
			return false;
		}
	}

	public ChessBoard() {
		board = new char[N][];
		for (int i = 0; i < N; i++) {
			board[i] = new char[N];
			for (int j = 0; j < N; j++)
				board[i][j] = BLANK;
		}
	}

	public void disp() {
		for (char[] cs : board) {
			for (char c : cs)
				System.out.print(c + " ");
			System.out.println();
		}
	}

	public ChessBoard deepCopy() {
		// oos -> bos, bos->bis, ois -> bis
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(this);

			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bis);
			return (ChessBoard) ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

}
